package mymyoux.data
{
	import flash.net.SharedObject;
	import mymyoux.signals.Signal;
	
	/**
	 * Used by Cache class
	 */
	public class CachedVar
	{
		/**
		 * @private
		 */
		protected var _name:String;
		/**
		 * @private
		 */
		protected var _signal:Signal;
		/**
		 * SharedObject which is manipulated by the SharedVar
		 */
		protected var _cache:SharedObject;
		/**
		 * Create an instance of SharedVar
		 * @param name Var's name
		 * @param cache Cache class
		 */
		public function CachedVar(name:String, cache:Cache)
		{
			_name = name;
			_signal = new Signal(Object);
		//	cache.nameChanged.add(onSharedNameChanged);
			_cache = SharedObject.getLocal(cache.name);
		}
		/**
		 * Called when the linked cache class has updated its name.
		 * Dispatches a valueChanged signal if var's value has changed
		 * @param name New name of sharedLocalObject
		 * @see #valueChanged
		 */
		protected function onSharedNameChanged(name:String):void
		{
			var value:* = this.value;
			_cache = SharedObject.getLocal(name);
			if(value != this.value)
			{
				_signal.dispatch(_name,this.value);
			}
		}
		/**
		 * Var's name
		 */
		public function get name():String
		{
			return _name;
		}
		/**
		 * Var's value.
		 * Dispatches a valueChanged signal if var's value has changed
		 */
		public function get value():*
		{
			return _cache.data[_name];
		}
		public function set value(value:*):void
		{
			if(_cache.data[_name] != value)
			{
				_cache.data[_name] = value;
				_cache.flush();
				_signal.dispatch(value);
			}
			
		}
		/**
		 * Signal that dispatches when var's value is changed.
		 */
		public function get valueChanged():Signal
		{
			return _signal;
		}

	}
}